import React, { Component } from "react"
import { EventKey } from "../consts"
import Api from "../lib/api/api"
import Global from "../lib/global"
import CouponModel from "../lib/models/coupon_model"
import CouponItem from "./coupon-item"
import ScrollView from "./scroll-view"
import Sheet from "./sheet"
import Taro from '@tarojs/taro'
import "./sheet-get-coupon.scss"

interface SheetCouponState {

    models?: CouponModel[]
}

class SheetCoupon extends Component<{}, SheetCouponState> {

    sheetRef = React.createRef<Sheet>()

    constructor(props) {
        super(props)
        this.state = {

        }
    }

    show = () => {
        this.sheetRef.current?.show()
    }

    /**
     * 请求优惠券列表
     */
    requestCouponList = async () => {
        let res = await Api.goodsCouponList()
        if (!Api.handleResponse(res)) {
            return false
        }
        console.log(res)
        this.setState({
            models: res?.data.couponlist
        })
        return true
    }

    onCouponItemClick = (model: CouponModel) => {

        if (model.isget) {
            if (Number.parseInt(model.needscore) > 0) {
                Global.showToast("你已兑换过咯\r\n快去用掉吧~")
            } else {
                Global.showToast("你已领取过咯\r\n快去用掉吧~")
            }
            return
        }

        Api.goodsCouponGet({
            id: model.id
        }).then( res => {
            console.log('res', res)

            if (!Api.handleResponse(res)) {
                return
            }

            if (Number.parseInt(model.needscore) > 0) {
                Global.showToast("兑换成功")
            } else {
                Global.showToast("领取成功")
            }
            
            Taro.eventCenter.trigger(EventKey.CouponGetd)
            this.requestCouponList()
        })
    }

    render() {
        const { models } = this.state

        let children = new Array()
        if (models) {
            for(const model of models) {
                children.push(<CouponItem className="coupon-item" model={ model } onClick={ this.onCouponItemClick }/>)
            }
        }

        return (
            <Sheet title="领取优惠劵" ref={ this.sheetRef }>
                <ScrollView style={{maxHeight: '800rpx'}} scrollY>
                    { children }
                </ScrollView>
            </Sheet>
        )
    }
}

export default SheetCoupon